package leetcode.ge100;

class Solution_557 {
	public static void main(String[] args) {
		System.out.println(reverseWords(" Let's take LeetCode contest"));

	}

	public static String reverseWords(String s) {
		char[] cc = s.toCharArray();

		StringBuffer sb = new StringBuffer();

		int l = cc.length;

		boolean start = false;
		int startIndex = 0;

		for (int i = 0; i < l; i++) {
			char c = cc[i];
			if (c == ' ' && !start) {
				sb.append(" ");
			} else if (c == ' ' && start) {
				sb.append(reverse(s.substring(startIndex, i)));
				start = false;
			} else if (c != ' ' && !start) {
				startIndex = i;
				start = true;
			}
		}

		return new String(sb);
	}

	private static String reverse(String sss) {
		char[] cc = sss.toCharArray();
		int l = cc.length;

		char tmp = 1;

		int half = l / 2;
		for (int i = 0; i <= half; i++) {
			tmp = cc[i];
			cc[i] = cc[l - 1 - i];
			cc[l - 1 - i] = tmp;
		}
		return new String(cc);
	}

}
